package com.tgy.leetcode;

/**
 *
 * https://leetcode-cn.com/problems/reverse-linked-list-ii/
 *
 */

public class _92_反转链表_II {

    public static ListNode reverseBetween(ListNode head, int left, int right) {

        if (left == right) {

            return head;
        }

        ListNode dump = new ListNode();
        dump.next = head;

        ListNode node = dump;
        int index = 0;
        for (int i = 1; i < left; i++) {

            index++;
            node = node.next;
        }

        if (node == null || node.next == null) {

            return head;
        }

        ListNode preNode = null, curNode = node.next,nextNode = null;
        ListNode lastNode = node.next;

        while (index < right) {

            nextNode = curNode.next;
            curNode.next = preNode;
            preNode = curNode;
            curNode = nextNode;
            index++;
        }

        node.next = preNode;
        lastNode.next = curNode;

        return dump.next;
    }

    public static void main(String[] args) {

        int[] nums = {1,2,3,4,5,6};
        ListNode listNode = ListNode.general(nums);
        ListNode newListNode = reverseBetween(listNode, 1, 1);
        ListNode.printListNode(newListNode);
    }
}
